import {
	observable,
	action,
	computed,
	extendObservable
} from 'mobx';
import {
	Button,
	message,
	Modal
} from 'antd';
import {
	WeaForm,
	WeaTableNew,
	WeaLogView
} from 'comsMobx';
import {
	WeaTableEdit,
	WeaBrowser
} from 'ecCom';
import classnames from 'classnames';
import * as mobx from 'mobx';
import {
	authorized,
	detachable,
	checkAuthAndDetach
} from '../apis/common';
import {
	i18n
} from '../public/i18n';
import moment from 'moment';

const confirm = Modal.confirm;
const info = Modal.info;
const {
	LogStore
} = WeaLogView;

export default class HrmBaseStore {
	/********************* unobservable list *********************/
	toJS = mobx.toJS;
	moment = moment;
	tabConfig = { //模块主tab组件参数，通过继承来重写
		keyParam: 'viewCondition',
		activeTabKey: ''
	};
	basicDialogParams = {
		icon: "icon-coms-hrm",
		iconBgcolor: "#217346",
		style: {
			width: 520,
			height: 300
		},
		visible: false,
		title: '',
	}
	menuIconCollection = {
		save: 'icon-coms-Preservation',
		create: 'icon-coms-New-Flow',
		modify: 'icon-coms-edit',
		remove: 'icon-coms-Batch-delete',
		copy: 'icon-coms-form-copy',
		entry: 'icon-coms-edit',
		setting: 'icon-coms-Flow-setting',
		log: 'icon-coms-Print-log',
		multiModify: 'icon-coms-BatchEditing',
		import: ' icon-coms-leading-in',
		export: 'icon-coms-export',
		search: 'icon-coms-search',
		sync: 'icon-coms-Update-synchronization',
		nextStep: 'icon-coms-Next-step',
		lastStp: 'icon-coms-Last-step'
	}
	getBasicMenus = () => [{
		key: '97',
		content: i18n.button.collect(),
		icon: <i className='icon-coms-Collection'/>,
		disabled: true,
	}]
	menus = [ //右键菜单定义
		{
			key: '97',
			content: i18n.button.collect(),
			icon: <i className='icon-coms-Collection'/>,
			disabled: true,
		}
	];
	dialogPropsDef = {
		moduleName: 'hrm',
		visible: false,
		title: '',
		moreBtn: {
			datas: []
		},
		// hasScroll: true
	}
	refsDialogPropsDef = {
		moduleName: 'hrm',
		visible: false,
		title: '',
	}
	dateSwitchTypeList = ['year', 'month', 'week', 'day'];
	formTarget = {}; //form collection
	opId = null; //数据操作对象主键ID
	authorizationInfo = {};

	/**
	 * 权限验证
	 * @param  {String}   moduleName [模块名]
	 * @param  {Object}   params     [restful request url params]
	 * @param  {Function} callback   [验证通过后的callback function]
	 * @return {null}
	 */
	checkAuthorized = (moduleName, params, callback, apiMethod, needCheckDetachable = false) => {
		if (needCheckDetachable) {
			checkAuthAndDetach(moduleName, params, apiMethod).then(rs => {
				rs.map((result, index) => {
					if (result.status === '1') {
						switch (index) {
							case 0:
								const init = !result.hasRight;
								this.authorizationInfo = result;
								this.containerInitFinished = {
									...this.containerInitFinished,
									init,
									authorized: result.hasRight,
									userId: result.userId
								}
								this.containerInitFinished.authorized && callback && callback();
								break;
							case 1:
								this.containerInitFinished.detachable = result.detachable === '0' ? false : true
								break;
						}
					}
				})
			})
		} else {
			authorized(moduleName, params, apiMethod).then((data) => {
				if (data.status === '1') {
					const init = !data.hasRight;
					this.authorizationInfo = data;
					this.containerInitFinished = {
						init,
						authorized: data.hasRight
					}
					this.containerInitFinished.authorized && callback && callback();
				}
			}, error => {
				this.containerInitFinished = {
					init: true,
					authorized: false
				}
			});
		}
	}

	/**
	 * 获取激活的tab页下标
	 * @param  {Array} tabs [tabData数组]
	 * @param  {String} key [tabKey]
	 * @return {Integer} [tab下标]
	 */
	getTabIndex(tabs, key) {
		if (tabs != null && tabs.length > 0) {
			return _.findIndex(tabs, {
				viewCondition: key
			})
		}
		return -1;
	}

	/**
	 * 获取WeaTop按钮、WeaTab按钮以及右键菜单列表
	 * @param  {Object} tabConfig [description]
	 * @return {Object}           [description]
	 */
	btnsAndMenus = (tabConfig) => {
		let topBtnDef = [], //WeaTop按钮
			menuDef = [], //右键菜单
			tabBtnDef = []; //WeaTab按钮

		const activeTabIndex = this.getTabIndex(tabConfig.tabs, tabConfig.activeTabKey);
		if (tabConfig.activeTabKey === '' || activeTabIndex < 0) {
			return {
				btns: topBtnDef,
				menus: menuDef,
				tabBtnDef: tabBtnDef
			}
		}
		const tab = tabConfig.tabs[activeTabIndex];
		const {
			topButtonDef,
			tabButtonDef
		} = tab;
		topButtonDef && topButtonDef.map((def, idx) => { //组织WeaTop按钮
			const lbl = (typeof(def.label) == 'function' ? def.label() : def.label);
			switch (def.comType) {
				case 'button':
					let disabled = false;
					if (def.checkAction)
						disabled = this[def.checkAction];
					topBtnDef.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ol8syy@${idx}`} type={def.type} onClick={def.onClickHandle} disabled={disabled || def.disabled}>{lbl}</Button>);
					menuDef.push({ //组织右键菜单
						key: `$top-btn-${idx}`,
						content: lbl,
						icon: <i className={def.rightMenuIcon || def.icon}/>,
						onClick: def.onClickHandle,
						disabled: disabled || def.disabled || false
					})
					break;
				default:
					break;
			}
		});
		tabButtonDef && tabButtonDef.map((def, idx) => { //组织WeaTab按钮
			const lab = (typeof(def.label) == 'function' ? def.label() : def.label);
			switch (def.comType) {
				case 'button':
					let disabled = false;
					if (def.checkAction)
						disabled = this[def.checkAction];
					const classes = classnames({
						[def.icon]: true,
						'tabBtn': true,
						'tabBtn-active': !disabled,
						'tabBtn-disable': disabled
					});
					if (def.brower == null) {
						tabBtnDef.push(
							<i
			            	  className={classes}
			            	  title={lab}
			            	  onClick={!disabled ? def.onClickHandle : null} 
				            />
						);
					} else {
						switch (def.brower) {
							case 'authorization':
								tabBtnDef.push(
									<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@xn50k3@${idx}`}
										customized
										tabs={[{name: i18n.label.byList(), key: '1', dataParams: {list: 1}},{name: i18n.label.byAuthGroup(), key: '2'}]}
										title={i18n.label.selectAuthorization()}
										icon={'icon-coms-hrm'}
										iconBgcolor={'#217346'}
										type={'hrmRoleRight'}
										inputStyle={{width: 200}}
										onChange={(ids, names, datas) => def.onClickHandle(ids, names, datas)}
										isSingle={false}
									>
										<i
						            	  className={classes}
						            	  title={lab}
							            />
									</WeaBrowser>
								);
								// def.lableComs = <WeaBrowser
								// 		customized
								// 		tabs={[{name: i18n.label.byList, key: '1', dataParams: {list: 1}},{name: i18n.label.byAuthGroup, key: '2'}]}
								// 		title={i18n.label.selectAuthorization}
								// 		icon={'icon-coms-hrm'}
								// 		iconBgcolor={'#217346'}
								// 		type={'hrmRoleRight'}
								// 		inputStyle={{width: 200}}
								// 		onChange={(ids, names, datas) => def.onClickHandle(ids, names, datas)}
								// 		isSingle={false}
								// 	>
								// 		<div>{def.label}</div>
								// 	</WeaBrowser>
								break;
						}
					}
					// menuDef.push({ //组织右键菜单
					// 	key: `$tab-btn-${idx}`,
					// 	content: def.lableComs || def.label,
					// 	icon: <i className={def.rightMenuIcon || def.icon}/>,
					// 	onClick: def.brower == null ? def.onClickHandle : null,
					// 	disabled: disabled || def.disabled || false
					// })
					break;
				default:
					break;
			}
		});
		menuDef.push(...this.getBasicMenus()); //组织右键菜单
		return {
			btns: topBtnDef,
			menus: menuDef,
			tabBtnDef: tabBtnDef
		}
	}

	/**
	 * [description]
	 * @param  {String}   com      [dialog's name]
	 * @param  {Boolean}   val      [visible: true or false]
	 * @param  {String}   title    [dialog's title]
	 * @param  {Function} callback [callback function]
	 * @return {null}
	 */
	setDialogVisible = (com, val, title = '', callback) => {
		this.dialogParams[com] = {
			...this.dialogParams[com],
			visible: val,
			title: title
		};
		callback && callback();
	}

	confirmInfo = (props) => {
		confirm({ ...props,
			title: i18n.confirm.defaultTitle(),
			okText: i18n.button.ok(),
			cancelText: i18n.button.cancel()
		});
	}

	hint = (props) => {
		info({ ...props,
			title: i18n.confirm.defaultTitle(),
			okText: i18n.button.ok(),
			// style: {
			// 	zIndex: 10000,
			// 	parent: {
			// 		style: {
			// 			zIndex: 10000
			// 		}
			// 	}
			// },
		});
	}

	/**
	 * 初始化formStore
	 * @param  {String} formName [form's name]
	 * @param  {Array} fields   [form field definition]
	 * @return {null}
	 */
	setFormData = (formName, fields) => {
		this.formTarget[`${formName}Fields`] = fields;
		this.formTarget[formName] = new WeaForm();
		this.formTarget[formName].initFormFields(fields);
	}

	/**
	 * 请求高级搜索表单的通用方法
	 * @param  {String}   form     [form's name]
	 * @param  {Function}   api      [restful api function]
	 * @param  {Object}   params   [restful request url params]
	 * @param  {Function} callback [callback function]
	 * @return {null}
	 */
	requestFormData = (form, api, params = {}, callback) => {
		api(params).then((data) => {
			if (data.status === '1') {
				this.setFormData(form, data.formField);
				callback && callback();
			}
		}, error => {

		});
	}

	/**
	 * 获取表格数据的通用方法
	 * @param  {String} tableStore [tableStore's name]
	 * @param  {Function} api        [restful api function]
	 * @param  {Object} params     [restful request url params]
	 * @return {null}
	 */
	requestTableData = (tableStore, api, params = {}, callback) => {
		api(params).then(data => {
			if (data.status === '1') {
				tableStore.getDatas(data.sessionkey, 1);
				callback && callback();
			} else
				message.error(data.message);
		}, error => {
			message.error(i18n.message.actionError());
		});
	}

	showLog = (logTypeParams) => {
		window.setLogViewProps({
			visible: true,
			logStore: new LogStore(),
			...logTypeParams
		});
	}
	/********************* unobservable list *********************/

	/********************* observable list *********************/
	@observable containerInitFinished = { //模块初始化状态
		init: false,
		authorized: false,
		detachable: false
	}
	@observable topTabCount = {}; //WeaTab统计值
	@observable rDate = new Date().getTime(); //状态刷新，组件引用该值监听变化重新render
	@observable showError = new Date().getTime(); //状态刷新，组件引用该值监听变化重新render
	@observable dialogParams = {}; //模态框参数
	/********************* observable list *********************/

	/********************* action list *********************/
	@action definedColumn = (table) => {
		table.setColSetVisible(true);
		table.tableColSet(true);
	}
	/********************* action list *********************/

	/********************* tableEdit props & functions *********************/
	editTable = {}; //可编辑表格refs对象
	editTableConfig = { //WeaTableEdit参数定义，通过继承来重写
		showTitle: false,
		draggable: true,
		showAdd: false,
		showDelete: false,
		showCopy: false,
		deleteConfirm: true
	}

	/**
	 * 设置WeaTableEdit的refs对象
	 * @param  {Object} refs [WeaTableEdit]
	 */
	setEditTable = (refs, name) => {
		this.editTable[name] = refs;
	}

	/**
	 * 通过refs对WeaTableEdit进行添加行、删除行、复制行操作
	 * @param  {String} type [action]
	 */
	@action
	recordOP = (target, type, callback = null) => {
		switch (type) {
			case 'add':
				target.refs.edit.doAdd()
				break;
			case 'remove':
				target.refs.edit.doDelete()
				break;
			case 'copy':
				target.refs.edit.doCopy()
				break;
			case 'valid':
				return target.refs.edit.doRequiredCheck()
			default:
				break;
		}
	}

	generateTableEditRightMenuInfo = (tableConfig) => {
		let rightMenuInfo = [];
		const keys = Object.keys(tableConfig);
		keys.map((key, index) => {
			rightMenuInfo.push({
				key: `8${index + 1}`,
				disabled: tableConfig[key].disabled,
				content: tableConfig[key].content,
				icon: <i className={this.menuIconCollection[key]}/>,
				onClick: tableConfig[key].callback
			})
		})
		return rightMenuInfo;
	}

	generateTableSelectedData = (target) => {
		let selectedData = {};
		this.tableEditConfig[target].columns.map(column => {
			column.hasOwnProperty('checkType') && column.checkType === 'checkbox' && Object.assign(selectedData, {
				[column.dataIndex]: []
			})
		})
		return selectedData;
	}

	generateOtherParams = (componentType) => {
		let otherParams = {
			customProps: {
				'root': {
					viewAttr: 1
				}
			},
			optionManageProps: {
				dialogProps: {
					icon: "icon-coms-hrm",
					iconBgcolor: "#217346",
				}
			}
		}
		switch (componentType) {
			case 'input':
				Object.assign(otherParams.customProps, {
					'input': {
						viewAttr: 1
					},
					'input.text': {
						viewAttr: 1
					}
				});
				break;
			case 'select':
				Object.assign(otherParams.customProps, {
					'select': {
						viewAttr: 1
					}
				});
				break;
		}
		return otherParams;
	}

	convertData = (datas, target) => {
		let tData = [],
			selectedData = this.generateTableSelectedData(target);
		datas.map((data, index) => {
			let d = {};
			Object.assign(d, {
				...data.record,
				...data.props
			});
			delete d.key;
			const selectedDataKey = Object.keys(selectedData);
			selectedDataKey.map(key => {
				data.record.hasOwnProperty(key) && data.record[key] === '1' && selectedData[key].push(index);
			})

			if (data.hasOwnProperty('com')) {
				const keys = Object.keys(data.com);
				keys.map(key => {
					if (data.com[key].length > 0) {
						let comDef = data.com[key][0];
						if (comDef.type === 'CUSTOMFIELD' && data.hasOwnProperty(comDef.key) && data[comDef.key].length > 0) {
							Object.assign(d, {
								[comDef.key]: data[comDef.key],
							});
							Object.assign(comDef, {
								viewAttr: 1,
								otherParams: this.generateOtherParams(data[comDef.key][0])
							})
						} else if (comDef.type === 'INPUT' && key != 'fieldname') {
							comDef.otherParams = {
								inputType: window.inputType
							}
						}
					}
				})
				Object.assign(d, {
					com: data.com
				});
			}

			tData.push(d);
		})
		return {
			datas: tData,
			selectedData
		}
	}

	getLocale() {
		return {
			firstDayOfWeek: 0,
			lang: {
				format: {
					eras: [getLabel(383357, "公元前"), getLabel(383358, "公元")],
					months: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					shortMonths: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					weekdays: [getLabel(24626, "星期天"), getLabel(383399, "星期一"), getLabel(383400, "星期二"), getLabel(383402, "星期三"), getLabel(383403, "星期四"),
						getLabel(383404, "星期五"), getLabel(383405, "星期六")
					],
					shortWeekdays: [getLabel(16106, "周日"), getLabel(16100, "周一"), getLabel(16101, "周二"), getLabel(16102, "周三"), getLabel(16103, "周四"), getLabel(16104, "周五"),
						getLabel(16105, "周六")
					],
					veryShortWeekdays: [getLabel(16106, "周日"), getLabel(16100, "周一"), getLabel(16101, "周二"), getLabel(16102, "周三"), getLabel(16103, "周四"), getLabel(16104, "周五"), getLabel(16105, "周六")],
					ampms: [getLabel(383408, "上午"), getLabel(383409, "下午")],
					datePatterns: [`yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}' EEEE`, `yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}'`, "yyyy-M-d", "yy-M-d"],
					timePatterns: [`ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}' 'GMT'Z`, `ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}'`, "H:mm:ss", "ah:mm"],
					dateTimePattern: '{date} {time}'
				}
			},
		}
	}
	/********************* tableEdit props & functions *********************/
}